local require = require
local uu     = require("modules.commhm.utils")
local config = require("modules.business_common.business_config")
local http   = require("modules.business_common.utils.business_http")

local ngx = ngx
local curr = uu.now

local table = table
local pairs = pairs
local ipairs = ipairs
local tonumber = tonumber
local tostring = tostring
local loadstring = table.loadstring

-- WARN: 邮件功能需要找邮件服添加白名单
local FOO = {
    _VERSION    = '0.0.1',
    OVERDUE_SEC = 30*86400
}

local http_request = function( uin, request )
    if not (request and request.cmd) then
        return nil
    end

    request.uin  = uin

    local server = config.get_mail_server_url(uin)
    local response = uu.json2table(http.Get(server, request) or 'nil')
    if response and tonumber(response.result) == 0 then
        return true, response
    end

    -- 失败日志
    http.Log(uu.to_str({ server = server, request = request, response = response }))
    return false
end

-- WARN: 邮件功能需要找邮件服添加白名单
FOO.send_system_mail = function (mail_info, uin)
    uin = uin or ngx.ctx.m_params.uin
    local request = uu.table_value_copy(mail_info)
    request.cmd      = "send_mail_to_player"
    request.attach   = request.attach or ''
    request.title    = request.title  or ''
    request.body     = request.body   or ''
    request.from     = request.reason or ''
    request.end_time = request.end_time or (curr() + FOO.OVERDUE_SEC)

    local succ, response = http_request(uin, request)
    if not succ then
        return false
    end

    return true, response.unique_id or 0
end

local make_item_attach = function (itemlist)
    local attach = nil
    for _, item in pairs(itemlist) do
        attach = attach and "," or ""
        attach = attach .. item.id .. ':' .. item.num
    end
    return attach
end

-- items = {{id = 10001, num = 1},{id = 10001, num = 1}...}
FOO.send_items_mail = function (mail_info, items, uin)
    mail_info.attach = make_item_attach(items)
    return FOO.send_system_mail(mail_info, uin)
end

return FOO